﻿#include <signal.h>
#include <stdlib.h>

#include "bjglobal.h"

IMySQL BJGlobal::dbconn;
BjConfig BJGlobal::config;

void BJGlobal::makeIndependent()
{
    pid_t pid;

    pid = fork();
    if (pid > 0)   //father
    {
        exit(0);
    }
    setsid();
    setpgrp();
    signal(SIGHUP, SIG_IGN);

    pid = fork();
    if (pid > 0)
    {
        exit(0);
    }
}

bool BJGlobal::inintDB ()
{
    InfoLog ( "开始初始化数据库连接......" );

    bool isTestDB = false;
    std::string traceDB, traceUser, tracePwd;
    std::string traceDBHost = "localhost";
    int dbPort = 3306;
    
    if ( !config.getBoolConfig( "USE_TEST_DB", isTestDB ) ) return false;
    if ( !isTestDB )
    {
        if ( !config.getStringConfig( "TRACE_DB_NAME", traceDB )
            || !config.getStringConfig( "TRACE_DB_USER", traceUser )
            || !config.getStringConfig( "TRACE_DB_PWD", tracePwd )
            )
        {
            return false;
        }
        config.getStringConfig( "TRACE_DB_HOST", traceDBHost );
        config.getIntConfig( "TRACE_DB_PORT", dbPort );
    }
    else
    {
        if ( !config.getStringConfig( "TRACE_TEST_DB_NAME", traceDB )
            || !config.getStringConfig( "TRACE_TEST_DB_USER", traceUser )
            || !config.getStringConfig( "TRACE_TEST_DB_PWD", tracePwd )
            )
        {
            return false;
        }
        config.getStringConfig( "TRACE_TEST_DB_HOST", traceDBHost );
        config.getIntConfig( "TRACE_TEST_DB_PORT", dbPort );
    }
    
    
    //初始化数据库连接。
    InfoLog ( "初始化到TRACE 数据库的连接[" << traceDBHost << "][" << traceDB << "]......" );
    dbconn.connect( traceDB, traceUser, tracePwd, traceDBHost, "utf8", dbPort );

    return true;
}

bool BJGlobal::init( const std::string& cfgFile, const std::string& logPath, bool isStdout )
{    
    //printf ( " ==== 开始初始化日志... ====\n" );
    
    if ( !initLog ( logPath.c_str(), isStdout, 50, 20 ) ) 
    {
        throw std::logic_error ("初始化日志失败!");
    }

    if ( !config.initialize ( cfgFile ) )
    {
        throw myexception ( "读取初始化配置文件失败!" );
    }

    bool isNeedDB = false;
    if ( !config.getBoolConfig( "NEED_CONNECT_DB", isNeedDB ) )
    {
        throw myexception ( "读取数据库配置出错!" );
    }

    if ( !isNeedDB )
    {
        InfoLog ( "不需要数据库连接" );
    }
    else
    {
        if ( !inintDB() )
        {
            throw myexception ( "初始化数据库失败!" );
        }
    }
    
    return true;
}



